# Copyright (C) ARM Limited, 2014-2016. All rights reserved.
#
# This example is intended to be built with ARM Compiler 6
#
# Environment variables for build options that the user might wish to change
#
# Variable     Example Value
# ----------   -------------
# APP          myapp.axf
# QUIET        @ for terse output, or leave blank for detailed output
# OPT_LEVEL    0, 1, 2 or 3
# DEFINES      -D MYDEFINE
# SUPPRESS     --diag_suppress=1234
# PLATFORM     CORTEXA (adds extra code for initialising Cortex-A35/A53/A57/A72/A73), or AEM

TOPDIR ?= $(PWD)/../..
LIBS ?=


APP ?= startup_AEMv8-FVP_AArch64_AC6.axf
# QUIET ?= @
OPT_LEVEL ?= 1
PLATFORM ?= AEM
OUTPUTCHAN ?= SEMIHOSTED

# Other switches the user should not normally need to change:
ARCH = armv8-a+sve
DEBUG_FLAGS = -g


ifeq "$(PLATFORM)" "CORTEXA"
	CPPFLAGS_EXTRA += -D CORTEXA
endif


ifeq ($(QUIET),@)
PROGRESS = @echo Compiling $<...
endif


CC = armclang
SRC_DIR = src
ASM_DIR = asm
OBJ_DIR = obj

INCLUDES = -I$(SRC_DIR)

define EOL =


endef

ifeq ($(OS),Windows_NT)
RM_FILES = $(foreach file,$(1),if exist $(file) del /q $(file)$(EOL))
RM_DIRS = $(foreach dir,$(1),if exist $(dir) rmdir /s /q $(dir)$(EOL))
else
RM_FILES = $(foreach file,$(1),rm -f $(file)$(EOL))
RM_DIRS = $(foreach dir,$(1),rm -rf $(dir)$(EOL))
endif

DEPEND_FLAGS = -MD -MF $@.d
CPPFLAGS = $(DEFINES) $(INCLUDES) $(DEPEND_FLAGS) $(CPPFLAGS_EXTRA)
CFLAGS = $(DEBUG_FLAGS) -O$(OPT_LEVEL) $(SUPPRESS)
ASFLAGS = $(DEBUG_FLAGS) $(SUPPRESS)
LDFLAGS = -Wl,--scatter=scatter.scat -e start64
TARGET_ARCH = --target=aarch64-arm-none-eabi -march=$(ARCH)

APP_C_SRC := $(wildcard $(SRC_DIR)/*.c)
APP_S_SRC := $(wildcard $(ASM_DIR)/*.S)
OBJ_FILES := $(APP_C_SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) \
             $(APP_S_SRC:$(ASM_DIR)/%.S=$(OBJ_DIR)/%.o)
DEP_FILES := $(OBJ_FILES:%=%.d)

.phony: all clean

all: $(APP)

$(APP): $(OBJ_DIR) $(OBJ_FILES) scatter.scat
	@echo Linking $@
	$(QUIET) $(CC) $(TARGET_ARCH) $(LDFLAGS) $(LIBS) --output $@ $(OBJ_FILES)
	@echo Done.

clean:
	$(call RM_DIRS,$(OBJ_DIR))
	$(call RM_FILES,$(APP))

$(OBJ_DIR):
	mkdir $@

$(OBJ_DIR)/%.o : $(SRC_DIR)/%.c | $(OBJ_DIR)
	$(PROGRESS)
	$(QUIET) $(CC) -c $(TARGET_ARCH) $(CPPFLAGS) $(CFLAGS) -o $@ $<

$(OBJ_DIR)/%.o : $(ASM_DIR)/%.S | $(OBJ_DIR)
	$(PROGRESS)
	$(QUIET) $(CC) -c $(TARGET_ARCH) $(CPPFLAGS) $(ASFLAGS) -o $@ $<

# Make sure everything is rebuilt if this makefile is changed
$(OBJ_FILES) $(APP): makefile

-include $(DEP_FILES)

help:
	@echo make [OPTIONS]
	@echo 'PLATFORM=   [AEM/CORTEXA]       Choose FVP target: AEMv8 or Cortex-A35/A53/A57/A72/A73'
	@echo ''
	@echo 'NOTE: The first value in the options indicates the default setting.'
